<template>
  <div class="rule-regulation">
    <!-- 搜索栏 -->
    <el-form
      :model="searchForm"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="制度标题">
        <el-input
          v-model="searchForm.title"
          placeholder="请输入标题"
          clearable
          size="small"
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="制度类型">
        <el-select v-model="searchForm.type" clearable size="small"  placeholder="请选择">
          <el-option
            v-for="item in detailList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>



    <!-- 按钮组 -->
    <div class="table-operations">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
      >新增</el-button
      >
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="mini"
        @click="handleBatchDelete()"
        :disabled="selectedIds.length === 0"
      >删除</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <!-- 添加选择列 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center"/>
      <el-table-column prop="title" label="标题" align="center"/>
      <el-table-column prop="type" label="类型" align="center">
        <template #default="scope">
          {{ show(scope.row.type) }}
        </template>
      </el-table-column>
<!--      <el-table-column prop="content" label="内容" align="center">-->
<!--        <template #default="scope">-->
<!--          <a href="javascript:" @click="handleDetail(scope.row)"-->
<!--             style="color: #00afff">{{ formatContent(scope.row.content) }}</a>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="createTime" label="创建时间" width="160" align="center"/>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
          <el-button
            size="mini"
            circle
            type="success"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
          <el-button
            size="mini"
            circle
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="55%"

      @closed="handleDialogClosed"
    >
      <span>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            @clear="selectClear"
            v-model="form.type"
            placeholder="请选择类型"
            value-key="dictValue"
            @change="handleTypeChange">  <!-- 添加这个属性 -->
            <el-option
              v-for="item in detailList"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <template>
              <div style="border: 1px solid #ccc;">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editor"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 500px; overflow-y: hidden;"
                    ref="editorRef"
                    v-model="form.content"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="onCreated"
                  />
              </div>
          </template>
        </el-form-item>
      </el-form>
        </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="isTypeCode">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<script>
import Vue from 'vue'
import {SlateElement} from '@wangeditor/editor'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {
  addRegulation,
  deleteRegulation,
  detailRegulation,
  getPage,
  updateRegulation,
  deleteList, getInfo
} from "@/api/regulatory/regulation";
import {getToken} from "@/utils/auth";

export default Vue.extend({
  components: {Editor, Toolbar},
  name: 'RuleRegulation',
  data() {

    return {
      selectedIds: [],// 选中的id
      detailList: [],// 规章制度类型列表
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            fieldName: 'file', // 自定义上传字段名
            maxFileSize: 1 * 1024 * 1024, //限制图片大小最大为1M
            server: process.env.VUE_APP_BASE_API + "/regulatory/regulation/upload", //上传图片的接口地址
            maxNumberOfFiles: 3, //最多可上传3个文件
            timeout: 5 * 1000, // 5 秒超时
            headers: {
              Authorization: 'Bearer ' + getToken()
            },
            customInsert(res, insertFn) {
              console.log(res)
              insertFn(res.data)  // 插入图片s
            },
          }
        }
      },
      mode: 'default', // or 'simple'
      typeCode: '1',
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        title: '',
        type: ''
      },
      tableData: [
        {id: 1, title: '人事规章制度', type: 1, content: '人事规章制度内容', createTime: '2021-01-01'}
      ],
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        title: '',
        type: '',
        content: ''
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'submit'}
        ],
        type: [
          {required: true, message: '请选择类型', trigger: 'submit'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'submit'}
        ]
      }
    }
  },

  created() {
    this.fetchData()
    this.regulations()
  },
  computed: {
    formType: {
      get() {
        // 如果是编辑状态，返回数字；如果是新增状态，返回字符串
        return this.typeCode === '2' ? Number(this.form.type) : this.form.type
      },
      set(value) {
        // 统一存储为字符串
        this.form.type = value.toString()
      }
    }
  },
  methods: {
    // 表格多选
    handleSelectionChange(selection) {
      // 确保获取到的是数字数组
      this.selectedIds = selection.map(item => Number(item.id))
    },

    // 批量删除方法
    async handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }

      try {
        await this.$confirm('确认删除选中的规章制度?', '提示', {
          type: 'warning'
        })

        const res = await deleteList(this.selectedIds)

        if (res.code === 200) {
          this.$message.success('删除成功')
          // 计算删除后的总数据量
          const newTotal = this.page.total - this.selectedIds.length
          // 计算当前页应该显示的数据量
          const currentPageSize = this.page.size
          // 计算最大页码
          const maxPage = Math.ceil(newTotal / currentPageSize)

          // 如果当前页大于最大页码，且不是第一页，则跳转到前一页
          if (this.page.current > maxPage && this.page.current > 1) {
            this.searchForm.pageNum = this.page.current - 1
          }

          await this.fetchData()
          this.selectedIds = []
        } else {
          this.$message.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error('批量删除错误:', error)
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    show(type) {
      for (let i = 0; i < this.detailList.length; i++) {
        if (this.detailList[i].dictValue == type) {
          console.log(this.detailList[i].dictLabel)
          return this.detailList[i].dictLabel
        }
      }
    },
    regulations() {
      detailRegulation().then(res => {
        this.detailList = res.data.list.map(item => ({
          ...item,
          dictValue: Number(item.dictValue)  // 确保是数字类型
        }))
      })
    },
    selectClear() {//下拉框取消查询
      this.fetchData()
    },
    isTypeCode() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.typeCode === '1') {
            this.add()
          }
          if (this.typeCode === '2') {
            this.update()
          }
          if (this.typeCode === '3') {
            this.dialogVisible = false
          }
        } else {
          return false
        }
      })
    },
    //内容判断
    formatContent(content) {
      if (!content) return '';
      // 移除HTML标签
      const plainText = content.replace(/<[^>]+>/g, '');
      // 截取前五个字符并添加省略号
      return plainText.length > 5 ? plainText.substr(0, 5) + '...' : plainText;
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },

    // 获取数据
    async fetchData() {
      try {
        // 这里调用后端API
        getPage(this.searchForm).then(res => {
          this.tableData = res.data.records
          this.page.total = res.data.total
          this.page.current = res.data.current
          this.page.size = res.data.size

        })
      } catch (error) {
        this.$message.error('获取数据失败')
      }
    },

    // 搜索
    handleSearch() {
      this.page.current = 1
      this.fetchData()
    },
    // 重置按钮操作
    resetQuery() {
      // 重置搜索表单数据
      this.searchForm = {
        pageNum: 1,
        pageSize: 10,
        title: '',
        type: ''
      }

      // 重置表单验证
      if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields()
      }

      // 触发搜索
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增规章制度'
      this.form = {
        id: null,
        title: '',
        type: undefined,
        content: ''
      }
      this.typeCode = '1'
      this.dialogVisible = true

    },

    handleEdit(row) {
      this.dialogTitle = '编辑规章制度'

      getInfo(row.id).then(res =>{
        this.form = res.data
      })
      // 等待DOM更新后重置表单
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.resetFields()
          this.$refs.formRef.clearValidate()
        }
        // 清空编辑器内容
        if (this.editor) {
          this.editor.setHtml('')
        }
      })
        // 记录 editor 实例，重要！

      this.typeCode = '2'
      this.dialogVisible = true
    },

// 关闭弹窗时的处理
    handleDialogClosed() {
      // 清空表单数据
      this.form = {
        id: null,
        title: '',
        type: undefined,
        content: ''
      }

      // 重置表单验证状态
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
        this.$refs.formRef.clearValidate()
      }
    },
    handleTypeChange(val) {
      if (!val) {
        this.$refs.formRef.validateField('type')
      }
    },
    //详情
    handleDetail(row) {
      this.dialogTitle = '查看规章制度'
      this.form = {...row}
      this.typeCode = '3'
      this.dialogVisible = true
    },
    //添加
    add() {
      addRegulation(this.form).then(response => {
        if (response.code === 200) {  // 假设 200 是成功状态码
          this.$message.success('添加成功')
          this.dialogVisible = false  // 先关闭弹窗
          this.fetchData()  // 再刷新数据
        } else {
          this.$message.error(response.msg || '添加失败')
        }
      })
    },
    //修改
    update() {
      updateRegulation(this.form).then(response => {
        if (response.code === 200) {
          this.$message.success('修改成功')
          this.dialogVisible = false  // 先关闭弹窗
          this.fetchData()  // 再刷新数据
          this.beforeDestroy()
          // this.$nextTick(() => {
          //   if (this.$refs.formRef) {
          //     this.$refs.formRef.resetFields()
          //     this.$refs.formRef.clearValidate()
          //   }
          //   // 清空编辑器内容
          //   if (this.editor) {
          //     this.editor.setHtml('')
          //   }
          // })
        } else {
          this.$message.error(response.msg || '修改失败')
        }
      })
    },
    // 删除
    // 单个删除方法也需要同样的逻辑
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该规章制度?', '提示', {
          type: 'warning'
        })
        const res = await deleteRegulation(row.id)
        if (res.code === 200) {
          this.$message.success('删除成功')

          // 计算删除后的总数据量
          const newTotal = this.page.total - 1
          // 计算当前页应该显示的数据量
          const currentPageSize = this.page.size
          // 计算最大页码
          const maxPage = Math.ceil(newTotal / currentPageSize)

          // 如果当前页大于最大页码，且不是第一页，则跳转到前一页
          if (this.page.current > maxPage && this.page.current > 1) {
            this.searchForm.pageNum = this.page.current - 1
          }

          await this.fetchData()
        } else {
          this.$message.error(res.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        if (this.form.id) {
          await this.$api.updateRuleRegulation(this.form)
        } else {
          await this.$api.createRuleRegulation(this.form)
        }
        this.$message.success(this.form.id ? '更新成功' : '新增成功')
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        this.$message.error(this.form.id ? '更新失败' : '新增失败')
      }
    },

    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.fetchData()
    }
  },
  beforeDestroy() {
    if (this.editor) {
      console.log('销毁编辑器')
      this.editor.destroy()
      this.editor = null
    }
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
    // }, 1500)
    this.fetchData()
  }

})
</script>

<style scoped>
/* 基础布局 */
.rule-regulation {
  padding: 20px;
}

/* 搜索栏 */
.search-bar {
  margin-bottom: 16px;
  margin-left: -60px; /* 向左移动搜索栏 */
  display: flex;
  gap: 8px;
}

/* 搜索栏按钮样式 */
.search-bar {
  .el-button {
    margin-left: 8px;
  }

  /* 重置按钮样式 */
  .el-button--default {
    background: #F5F7FA;
    border-color: #DCDFE6;

    &:hover {
      background: #EBEEF5;
      border-color: #C6E2FF;
      color: #409EFF;
    }
  }
}

/* 按钮图标间距 */
.el-button [class*="el-icon-"] + span {
  margin-left: 5px;
}

/* 新增按钮 */
.add-button {
  margin-bottom: 16px;
}

/* 按钮组统一样式 */
.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 统一按钮样式 */
.operation-btn {
  height: 28px !important;  /* 强制统一高度 */
  line-height: 28px !important;
  padding: 0 15px !important;
  font-size: 12px !important;
}

/* 批量删除按钮样式 */
.operation-btn.el-button--danger {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
  color: #FFFFFF !important;
}

/* 批量删除按钮禁用状态 */
.operation-btn.el-button--danger.is-disabled {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: #FFFFFF !important;
}

/* 批量删除按钮悬浮状态 */
.operation-btn.el-button--danger:not(.is-disabled):hover {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}
/* 表格基础样式 */
::v-deep( .el-table) {
  border: 1px solid #EBEEF5 !important;
  border-bottom: none !important;
}

/* 清除所有默认边框 */
::v-deep (.el-table--border .el-table--group) {
  border: none !important;
}

/* 去除表格的伪元素边框 */
::v-deep ( .el-table::before,
 .el-table::after ){
  display: none !important;
}

/* 单元格边框处理 */
::v-deep ( .el-table td.el-table__cell,
 .el-table th.el-table__cell) {
  border: none !important;
}

/* 只保留行下方边框线 */
::v-deep (.el-table tr ){
  border-bottom: 1px solid #EBEEF5 !important;
}

::v-deep ( .el-table__row:last-child ){
  border-bottom: none !important;
}

/* 表头样式 */
::v-deep ( .el-table__header-wrapper th.el-table__cell) {
  background-color: #f5f7fa !important;
  border-bottom: 1px solid #EBEEF5 !important;
  color: #606266;
  font-weight: normal;
}

/* 调整单元格内容的间距和对齐 */
::v-deep ( .el-table .cell ){
  padding: 0 8px;
  white-space: nowrap;
  text-align: center;
}

/* 确保没有固定列的边框 */
::v-deep ( .el-table__fixed-right::before,
.el-table__fixed::before) {
  display: none !important;
}

/* 操作按钮样式调整 */
.edit-btn,
.delete-btn {
  padding: 4px;
  height: 24px;
  width: 24px;
  margin: 0 4px;
}

.edit-btn {
  background-color: #67C23A;
  color: #fff;
}

.delete-btn {
  background-color: #F56C6C;
  color: #fff;
}

/* 操作按钮 */
.edit-btn {
  background-color: #67C23A;
  color: #fff;
  width: 24px;
  height: 24px;
  padding: 0;
  margin-right: 8px;
}

.delete-btn {
  background-color: #F56C6C;
  color: #fff;
  width: 24px;
  height: 24px;
  padding: 0;
}

/* 分页器 */
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 16px;
}

/* 表单元素 */
::v-deep(.el-input__inner),
::v-deep(.el-button) {
  height: 32px;
}

::v-deep(.el-select) {
  width: 180px;
}

/* 编辑器容器 */
.editor-container {
  border: 1px solid #ccc;
}

::v-deep(.el-table__cell) {
  text-align: center;
}

::v-deep(.el-table .cell) {
  padding: 0 8px;
  white-space: nowrap; /* 防止文字换行 */
}


</style>
